package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author spt
 * @description 预约设置控制器
 * @date
 **/
@RestController
@RequestMapping("/ordersetting")
@Slf4j
public class OrderSettingController {
    @Autowired
    private OrderSettingService orderSettingService;

    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String year, String month) {
        log.info("[日期是]{}年{}月", year, month);
        //获取时间,可预约人数
        List<OrderSetting> orderSettingByMonth = orderSettingService.getOrderSettingByMonth(year, month);
        List<Map<String, Integer>> list = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingByMonth) {
            Map<String, Integer> map = new HashMap<>();
            String day = String.format("%te", orderSetting.getOrderDate());
            map.put("date", Integer.valueOf(day));
            map.put("number", orderSetting.getNumber());
            map.put("reservations", orderSetting.getReservations());
            list.add(map);
        }
        //返回结果预约人数
        return new Result(true, MessageConst.GET_ORDERSETTING_SUCCESS, list);
    }

    /**
     * @description 获取excel中的所有预约日期和预约人数
     */

    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        //1.获取文件名
        String fileName = excelFile.getOriginalFilename();
        //2.获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //3.判断文件后缀名
        if (!".xlsx".equals(suffixName) && !".xls".equals(suffixName)) {
            throw new BusinessRuntimeException(MessageConst.IMPORT_ORDERSETTING_FAIL);
        }
        //4.获取文件输入流
        InputStream inputStream = null;
        try {
            inputStream = excelFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //5.根据文件后缀名创建Workbook
        Workbook workbook = null;
        try {
            if (".xlsx".equals(suffixName)) {
                workbook = new XSSFWorkbook(inputStream);
            } else if (".xls".equals(suffixName)) {
                workbook = new HSSFWorkbook(inputStream);
            }
        } catch (IOException e) {
            throw new BusinessRuntimeException(MessageConst.IMPORT_ORDERSETTING_FAIL);
        }
        //6.获取sheet页
        Sheet sheet = workbook.getSheetAt(0);
        //7.获取sheet页中的所有行
        int rows = sheet.getPhysicalNumberOfRows();
        if (rows <= 1) {
            throw new BusinessRuntimeException(MessageConst.IMPORT_ORDERSETTING_FAIL);
        }
        //8.获取sheet页中的所有列
//        int columns = sheet.getRow(0).getPhysicalNumberOfCells();
        //9.遍历所有行
        List<OrderSetting> orderSettingList = new ArrayList<>();
        for (int i = 1; i < rows; i++) {
            //10.获取行
            Row row = sheet.getRow(i);
            //11.获取每一行的每一列
            Date orderDate = row.getCell(0).getDateCellValue();
            int number = (int) row.getCell(1).getNumericCellValue();
            if (number < 1) {
                throw new BusinessRuntimeException(MessageConst.ORDER_SETTING_NUMBER_ERROR);
            }
            //12.创建OrderSetting对象
            OrderSetting orderSetting = new OrderSetting(orderDate, number);
            orderSettingList.add(orderSetting);
        }
        if (orderSettingList.size() == 0) {
            throw new BusinessRuntimeException(MessageConst.IMPORT_ORDERSETTING_FAIL);
        }
        //13.调用service层的方法
        orderSettingService.add(orderSettingList);
        return new Result(true, MessageConst.IMPORT_ORDERSETTING_SUCCESS);
    }

    //SneakyThrows解决parse异常
    @SneakyThrows
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody Map map) {
        //接收日期，将string类型变成date类型
        String od = map.get("orderDate").toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date orderDate = sdf.parse(od);

        //接收设置预约人数,转换成string类型
        String num = map.get("number").toString();
        Long number = null;
        //string转换成long类型，然后和int类型最大值作比较
        if(( number =Long.valueOf(num))>=Integer.MAX_VALUE){
            throw new BusinessRuntimeException("回火星去");
        }

            orderSettingService.editNumByDa(orderDate,Integer.parseInt(number.toString()));

            return new Result(true, MessageConst.ORDERSETTING_SUCCESS);

        }


    }



